<template>
  <div>
    <!-- M面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 接收数据 -->
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button type="info" icon="el-icon-delete" circle @click="deleUser(scope.row.id)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="assigningRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totals"
      ></el-pagination>
    </el-card>

    <!-- 添加按钮对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="dialogClose">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormCheck">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogCheck">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="assigningRolesDialogVisible"
      width="50%"
      @close="assRoleDialogClose"
    >
      <div class="assigning_p">
        <p>用户名:{{assRolesMess.username}}</p>
        <p>角色:{{assRolesMess.role_name}}</p>
        <p>
          权限:
          <el-select v-model="selectdRoleId" placeholder="请选择">
            <el-option
              v-for="item in userRoleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assigningRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证规则，验证规则的值，回调
    var checkEmail = (rule, value, callback) => {
      const regEmail = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/

      if (regEmail.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      const regIphone = /0?(13|14|15|17|18|19)[0-9]{9}/

      if (regIphone.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法手机号'))
    }
    return {
      // 列表请求参数
      queryInfo: {
        // 搜索关键字
        query: '',
        // 当前页码
        pagenum: 1,
        // 当前页码多少条
        pagesize: 2
      },
      // 用户列表
      userList: [],
      // 总条数
      totals: 0,
      // 添加按钮显示
      dialogVisible: false,
      // 修改按钮显示
      editDialogVisible: false,
      // 分配角色显示
      assigningRolesDialogVisible: false,
      // 保存分配角色的用户信息
      assRolesMess: {},
      // 保存角色权限列表
      userRoleList: [],
      // 已经选中的权限id
      selectdRoleId: '',
      // 添加用户
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 查询id后的数据
      editForm: {},
      // 添加用户的校验
      userRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 查询id后的数据的校验
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.totals = res.data.total
    },
    // 当前页多少条
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 当前页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 用户状态
    async userStateChange(state) {
      const { data: res } = await this.$http.put(
        `users/${state.id}/state/${state.mg_state}`
      )
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state
        return this.$message.error('修改用户状态失败')
      }
      this.$message.success('修改用户状态成功')
    },
    // 清空表单
    dialogClose() {
      this.$refs.userFormRef.resetFields()
    },
    // 表单预校验
    dialogFormCheck() {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return false
        // 发送请求
        const { data: res } = await this.$http.post('users', this.userForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 显示修改用户对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询失败')
      }
      this.editForm = res.data
    },
    // 修改表单重置
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改表单预校验
    editDialogCheck() {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return false
        // 发请求提交
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户状态失败')
        }
        // console.log(res)
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新列表
        this.getUserList()
        // 提示信息
        this.$message.success('修改用户成功')
      })
    },
    // 删除角色
    async deleUser(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除账户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      // console.log('确认删除')
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // 刷新列表
      this.getUserList()
      // 提示信息
      this.$message.success('删除成功')
    },
    // 点击分配角色按键
    async assigningRoles(scope) {
      this.assigningRolesDialogVisible = true
      this.assRolesMess = scope
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      // 保存角色列表
      this.userRoleList = res.data
      // console.log(this.userRoleList)
    },
    // 分配角色弹窗点击确定
    async saveRoleInfo() {
      //  确认后发请求
      const { data: res } = await this.$http.put(
        `users/${this.assRolesMess.id}/role`,
        {
          rid: this.selectdRoleId
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限失败')
      }
      this.$message.success('更新成功')
      this.assigningRolesDialogVisible = false
      this.getUserList()
    },
    // 分配角色弹窗清空
    assRoleDialogClose() {
      this.assRolesMess = {}
      this.selectdRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.assigning_p {
  p {
    margin-top: 9px;
  }
}
</style>
